package com.streamkar.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.streamkar.common.config.session.UserSession;
import com.streamkar.common.es.ESRestClient;
import com.streamkar.common.es.ExecuteDslComponent;
import com.streamkar.constant.Constants;
import com.streamkar.constant.ReturnCode;
import com.streamkar.entity.base.IdRequest;
import com.streamkar.entity.base.Response;
import com.streamkar.entity.base.ResponseData;
import com.streamkar.entity.request.CreateIncentiveRequest;
import com.streamkar.entity.request.UpdateIncentiveRequest;
import com.streamkar.service.AccountService;
import com.streamkar.service.AgencyService;
import com.streamkar.util.EsUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName IncentiveRest
 * @Description
 * @Author tyfrost
 * @Date 2018/11/13 下午11:50
 * @Version 1.0
 */
@RestController
public class IncentiveRest {

    private static final Logger LOGGER = LoggerFactory.getLogger(IncentiveRest.class);

    @Autowired
    AccountService accountService;

    @Autowired
    Environment environment;

    @Autowired
    AgencyService agencyService;

    @Autowired
    EsUtil esUtil;

    @Autowired
    ESRestClient esRestClient;

    @Autowired
    UserSession userSession;

    @Autowired
    ExecuteDslComponent executeDslComponent;

    @RequestMapping(value = "/admin/incentive", method = RequestMethod.POST)
    @ResponseBody
    public Response addIncentive(@RequestBody @Valid CreateIncentiveRequest createIncentiveRequest) {
        ResponseData<String> responseData = new ResponseData<>();
        Integer userId = userSession.getUserId();
        IndexRequest indexRequest = new IndexRequest(Constants.INCENTIVE_INDEX, Constants.INCENTIVE_TYPE);
        JSONObject jsonObject = createIncentiveRequest.toEvent(userId);

        try {
            if (esUtil.belongCalendar(new Date(), createIncentiveRequest.getStartDate(), createIncentiveRequest.getEndDate())) {
                jsonObject.put("activate", 1);
            } else {
                jsonObject.put("activate", 0);
            }
        } catch (Exception e) {
            LOGGER.error("check date catch an exception..", e);
            responseData.setCode(ReturnCode.PARAMETER_FORMAT_ERROR);
            return responseData;
        }

        indexRequest.source(jsonObject);
        try {
            IndexResponse indexResponse = esRestClient.getRestClient().index(indexRequest, RequestOptions.DEFAULT);
            LOGGER.info("invoke index success..return:{}", indexResponse.toString());
            responseData.setData(indexResponse.getId());
        } catch (Exception e) {
            responseData.setCode(ReturnCode.FAIL);
            LOGGER.error("invoke index catch an exception..", e);
        }

        return responseData;
    }

    @RequestMapping(value = "/admin/incentive", method = RequestMethod.PUT)
    @ResponseBody
    public Response editIncentive(@RequestBody @Valid UpdateIncentiveRequest updateIncentiveRequest) {
        Response response = new Response();
        Integer userId = userSession.getUserId();
        UpdateRequest updateRequest = new UpdateRequest(Constants.INCENTIVE_INDEX, Constants.INCENTIVE_TYPE, updateIncentiveRequest.getId());
        updateRequest.doc(updateIncentiveRequest.toEvent(userId));
        try {
            UpdateResponse updateResponse = esRestClient.getRestClient().update(updateRequest, RequestOptions.DEFAULT);
            LOGGER.info("invoke update success..return:{}", updateResponse.toString());
        } catch (Exception e) {
            LOGGER.error("invoke update catch an exception..", e);
            response.setCode(ReturnCode.FAIL);
        }
        return response;
    }

    @RequestMapping(value = "/admin/incentive", method = RequestMethod.DELETE)
    public Response deleteIncentive(@Valid IdRequest idRequest) {
        Response response = new Response();
        Integer userId = userSession.getUserId();
        UpdateRequest updateRequest = new UpdateRequest(Constants.INCENTIVE_INDEX, Constants.INCENTIVE_TYPE, idRequest.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 1);
        jsonObject.put("updateUserId", userId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jsonObject.put("updateDate", sdf.format(new Date()));
        updateRequest.doc(jsonObject);
        try {
            UpdateResponse updateResponse = esRestClient.getRestClient().update(updateRequest, RequestOptions.DEFAULT);
            LOGGER.info("invoke delete incentive success..return:{}", updateResponse.toString());
        } catch (Exception e) {
            LOGGER.error("invoke delete incentive catch an exception..", e);
            response.setCode(ReturnCode.FAIL);
        }
        return response;
    }

    @RequestMapping(value = "/incentive", method = RequestMethod.GET)
    public Response queryIncentive() {
        ResponseData<Object> responseData = new ResponseData<>();
        String dsl = "{\"query\":{\"bool\":{\"must\":[{\"term\":{\"activate\":1}},{\"term\":{\"status\":0}}]}},\"from\":0,\"size\":30,\"sort\":{\"startTime\":{\"order\":\"desc\"}}}";
        JSONArray jsonArray = executeDslComponent.executeDsl(Constants.INCENTIVE_INDEX, dsl);
        responseData.setData(jsonArray);
        return responseData;
    }

    @RequestMapping(value = "/incentive/{incentiveId}", method = RequestMethod.GET)
    public Response queryIncentiveDetail(@PathVariable(value = "incentiveId") final String incentiveId) {
        ResponseData<Object> responseData = new ResponseData<>();
        String dsl = "{\"query\":{\"bool\":{\"must\":[{\"term\":{\"activate\":1}},{\"term\":{\"status\":0}},{\"term\":{\"_id\":\"{{incentiveId}}\"}}]}},\"from\":0,\"size\":1}";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("incentiveId", incentiveId);
        JSONArray jsonArray = executeDslComponent.executeDsl(Constants.INCENTIVE_INDEX, dsl, paramMap);
        if (!CollectionUtils.isEmpty(jsonArray)) {
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            jsonObject.put("id", incentiveId);
            responseData.setData(jsonObject);
        }
        return responseData;
    }
}
